<template>
  <div>

    <div class="container">
      <div class="handle-box">
        <el-input v-model="query.conferenceName" clearable placeholder="会议名称" style="width: 200px;" class="handle-input mr10"></el-input>
        <el-input v-model="query.participantName" clearable placeholder="用户姓名" style="width: 200px;" class="handle-input mr10"></el-input>
        <el-input v-model="query.idCardNumber" clearable placeholder="身份证号" style="width: 200px;" class="handle-input mr10"></el-input>
        <el-input v-model="query.licensePlate" clearable placeholder="车牌号" style="width: 200px;" class="handle-input mr10"></el-input>
        <el-select
          style="width: 200px;" class="handle-input mr10"
          v-model="query.assignmentType"
          placeholder="请选择分配类型"
          clearable
        >
          <el-option :label="'接站'" :value="0" />
          <el-option :label="'会议期间'" :value="1" />
          <el-option :label="'送站'" :value="2" />
        </el-select>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="addVisible = true">新增</el-button>
        <!-- ✅ 导入导出按钮 -->
        <!-- <el-button
          type="success"
          icon="el-icon-upload2"
          class="mr10"
          @click="$refs.excelInput.click()"
        >导入 Excel</el-button> -->
        <input
          type="file"
          ref="excelInput"
          style="display: none"
          accept=".xlsx, .xls"
          @change="importFromExcel"
        />
        <el-button
          type="warning"
          icon="el-icon-download"
          @click="exportToExcel"
        >导出 Excel</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">批量删除</el-button>
      </div>

      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <!-- <el-table-column prop="assignmentId" label="标识"></el-table-column> -->
        <el-table-column prop="conferences.conferenceName" label="会议名称"></el-table-column>
        <el-table-column prop="participants.fullName" label="用户姓名"></el-table-column>
        <el-table-column prop="participants.idCardNumber" label="身份证号"></el-table-column>
        <el-table-column prop="participants.transportType" label="交通类型"></el-table-column>
        <el-table-column prop="participants.flightTrainNumber" label="航班/车次号"></el-table-column>
        <el-table-column prop="participants.arrivalLocation" label="到达地点"></el-table-column>
        <el-table-column prop="participants.arrivalTime" label="到达时间" :formatter="formatDateTime"></el-table-column>
        <el-table-column prop="vehicles.licensePlate" label="车牌号"></el-table-column>
        <el-table-column prop="assignmentType" label="分配类型">
          <template slot-scope="scope">
            {{ scope.row.assignmentType === 0 ? '接站' : scope.row.assignmentType === 1 ? '会议期间' : scope.row.assignmentType === 2 ? '送站' : '未知' }}
          </template>
        </el-table-column>        
        <el-table-column prop="notes" label="备注"></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.row.assignmentId)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="90px"
      >
        <!-- v-model 绑定 conferenceId，展示 label -->
        <el-form-item label="会议名称" prop="conferenceId">
          <el-select
            v-model="form.conferenceId"
            placeholder="请选择会议名称"
            filterable
            clearable
            style="width: 100%;"
          >
            <el-option
              v-for="conf in conferences"
              :key="conf.conferenceId"
              :label="conf.conferenceName"
              :value="conf.conferenceId"
            />
          </el-select>
        </el-form-item>
      
        <!-- 用户姓名 -->
        <el-form-item label="用户姓名" prop="participantId">
          <el-select
            v-model="form.participantId"
            placeholder="请选择用户姓名"
            filterable
            clearable
            style="width: 100%;"
          >
            <el-option
              v-for="user in users"
              :key="user.participantId"
              :label="user.fullName"
              :value="user.participantId"
            />
          </el-select>
        </el-form-item>
        <!-- 车牌号 -->
        <el-form-item label="车牌号" prop="vehicleId">
          <el-select
            v-model="form.vehicleId"
            placeholder="请选择车辆"
            filterable
            clearable
            style="width: 100%;"
          >
            <el-option
      v-for="car in vehicles"
      :key="car.vehicleId"
      :label="car.licensePlate"
      :value="car.vehicleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分配类型" prop="assignmentType">
          <el-select
            v-model="form.assignmentType"
            placeholder="请选择分配类型"
            clearable
            style="width: 100%;"
          >
            <el-option :label="'接站'" :value="0" />
            <el-option :label="'会议期间'" :value="1" />
            <el-option :label="'送站'" :value="2" />
          </el-select>
        </el-form-item>
        <!-- 备注 -->
        <el-form-item label="备注" prop="notes">
          <el-input
            type="textarea"
            v-model="form.notes"
            placeholder="请输入备注"
            :rows="3"
          />
        </el-form-item>
      </el-form>
    
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增弹出框 -->
    <el-dialog title="新增" :visible.sync="addVisible" width="30%">
      <el-form
        ref="form"
        :model="addForm"
        :rules="rules"
        label-width="90px"
      >
        <!-- 会议名称 -->
        <el-form-item label="会议名称" prop="conferenceId">
          <el-select
            v-model="addForm.conferenceId"
            placeholder="请选择会议名称"
            filterable
            clearable
            style="width: 100%;"
          >
            <el-option
              v-for="conf in conferences"
              :key="conf.conferenceId"
              :label="conf.conferenceName"
              :value="conf.conferenceId"
            />
          </el-select>
        </el-form-item>
      
        <!-- 用户姓名 -->
        <el-form-item label="用户姓名" prop="participantId">
          <el-select
            v-model="addForm.participantId"
            placeholder="请选择用户姓名"
            filterable
            clearable
            style="width: 100%;"
          >
            <el-option
              v-for="user in users"
              :key="user.participantId"
              :label="user.fullName"
              :value="user.participantId"
            />
          </el-select>
        </el-form-item>
      
        <!-- 车牌号 -->
        <el-form-item label="车牌号" prop="vehicleId">
          <el-select
            v-model="addForm.vehicleId"
            placeholder="请选择车辆"
            filterable
            clearable
            style="width: 100%;"
          >
            <el-option
              v-for="car in vehicles"
              :key="car.vehicleId"
              :label="car.licensePlate"
              :value="car.vehicleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分配类型" prop="assignmentType">
          <el-select
            v-model="addForm.assignmentType"
            placeholder="请选择分配类型"
            clearable
            style="width: 100%;"
          >
            <el-option :label="'接站'" :value="0" />
            <el-option :label="'会议期间'" :value="1" />
            <el-option :label="'送站'" :value="2" />
          </el-select>
        </el-form-item>
        <!-- 备注 -->
        <el-form-item label="备注" prop="notes">
          <el-input
            type="textarea"
            v-model="addForm.notes"
            placeholder="请输入备注"
            :rows="3"
          />
        </el-form-item>
      </el-form>
    
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd">取 消</el-button>
        <el-button type="primary" @click="saveAdd">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import requests from '../utils/request'
import dayjs from 'dayjs';


export default {
    name: 'basetable',
    data() {
      return {
        query: {
          conferenceName:'',
          participantName:'',
          idCardNumber:'',
          licensePlate:'',
          pageIndex: 1,
          pageSize: 30
        },
        tableData: [],
        multipleSelection: [],
        exportData: [],
        editVisible: false,
        addVisible: false,
        pageTotal: 0,
        form: {
          assignmentId: null,
          conferenceId: null,
          participantId: null,
          participants: {
            participantName: '',
          },
          vehicleId: null,
          notes: '',
        },
        conferences:{},
        users:{},
        vehicles:{},
        addForm: {
          conferenceId: '',
          participantId: '',
          vehicleId: '',
          notes: '',
          assignmentType:''
        },
        idx: -1,
        id: -1,
        rules: {
          conferenceId: [{ required: true, message: '请选择会议名称', trigger: 'change' }],
          participantId: [{ required: true, message: '请选择用户姓名', trigger: 'change' }],
          assignmentType: [{ required: true, message: '请选择分配类型', trigger: 'change' }],
          vehicleId: [{ required: true, message: '请选择车辆', trigger: 'change' }],
          notes: [{ max: 200, message: '备注不能超过200字', trigger: 'blur' }]
        }
      };
    },
    created() {
       this.loading()
    },
    methods: {
      //加载数据
      loading() {
        requests.get("/vehicleAssignment/pageSelect", {
          page: this.query.pageIndex,
          size: this.query.pageSize,
          conferenceName: this.query.conferenceName,
          participantName: this.query.participantName,
          idCardNumber: this.query.idCardNumber,
          licensePlate: this.query.licensePlate,
          assignmentType: this.query.assignmentType
        }).then(res=>{
          this.pageTotal = res.total,
          this.tableData = res.data
        });
        requests.get("/participants/selectAllParticipant").then(res=>{
          this.users = res
        })
        requests.get("/vehicles/selectAllVehicle").then(res=>{
          this.vehicles = res
        })
        requests.get("/conferences/selectAll").then(res=>{
          this.conferences = res
        })
      },
      // 触发搜索按钮
      handleSearch() {
          this.loading();
      },
      //时间格式化
      formatDateTime(cellValue) {
        if (!cellValue) return '';
        const date = new Date(cellValue);
        const pad = n => n.toString().padStart(2, '0');
        return `${date.getFullYear()}/${pad(date.getMonth() + 1)}/${pad(date.getDate())} ` +
               `${pad(date.getHours())}:${pad(date.getMinutes())}`;
      },
      // 删除操作
      handleDelete(row) {
        // 二次确认删除
        this.$confirm('确定要删除吗？', '提示', {
            type: 'warning'
        })
            .then(() => {
                requests.delete("/vehicleAssignment/delById",{
                  assignmentId: row
                }).then(res=>{
                  this.$message.success(res);
                  this.loading()
                })
            })
      },
      // 编辑操作
      handleEdit(row) {
        // 安全深拷贝 row 对象，避免响应式污染
        const newForm = JSON.parse(JSON.stringify(row));
        // 赋值给表单
        this.form = newForm;
        this.editVisible = true;
      },
      // 取消编辑
      cancelEdit() {
        // 失去当前聚焦
        document.activeElement && document.activeElement.blur();
      
        this.editVisible = false;
        // 重置表单（如果需要）
        this.$refs.form.resetFields();
      },
      // 保存编辑
      saveEdit() {
        // 先校验表单
        this.$refs.form.validate(valid => {
          if (!valid) {
            // 校验失败，不提交
            return;
          }
          // 校验成功，调用接口
          requests.post("/vehicleAssignment/edit", this.form)
            .then(res => {
              this.$message.success(res);  // 用 success 提示更合适
              this.editVisible = false;    // 请求成功后关闭弹窗
              this.loading();              // 刷新数据
            })
        });
      },
      // 分页导航
      handlePageChange(val) {
          this.query.pageIndex = val
          this.loading()
      },
      // 单选、多选改变时调用
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 批量删除
      handleBatchDelete() {
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请选择要删除的酒店');
          return;
        }
      
        this.$confirm(`确定删除这 ${this.multipleSelection.length} 项吗？`, '提示', {
          type: 'warning'
        })
          .then(() => {
            const ids = this.multipleSelection.map(item => item.assignmentId);
            requests.post('/vehicleAssignment/delByIds', ids)  // ✅ 注意这里直接传数组
              .then(res => {
                this.$message.success(res);
                this.loading(); // 重新加载表格
              })
          })
      },
      //新增操作
      handleAdd(row) {
        this.addForm = row;
        this.addVisible = true;
      },
      // 取消操作
      cancelAdd() {
        // 失去当前聚焦
        document.activeElement && document.activeElement.blur();
      
        this.editVisible = false;
        // 重置表单（如果需要）
        this.$refs.addForm.resetFields();
      },
      // 保存操作
      saveAdd() {
        // 先校验表单
        this.$refs.form.validate(valid => {
          if (!valid) {
            // 校验失败，不提交
            return;
          }
        
          // 校验成功，调用接口
          requests.post("/vehicleAssignment/add", this.addForm)
            .then(res => {
              this.$message.success(res);  // 用 success 提示更合适
              this.addVisible = false;    // 请求成功后关闭弹窗
              this.loading();              // 刷新数据
            })
        });
      },
      //导出
      exportToExcel() {
        requests.get("/vehicleAssignment/exportAssignmentInfor").then(res => {
          // 处理导出数据
          let exportData = res.map(row => {
            return {
              // 标识: String(row.assignmentId),
              // 会议标识: String(row.conferenceId),
              会议名称: row.conferences && row.conferences.conferenceName ? row.conferences.conferenceName : '',
              // 用户标识: String(row.participantId),
              用户姓名: row.participants && row.participants.fullName ? row.participants.fullName : '',
              身份证号: row.participants && row.participants.idCardNumber ? row.participants.idCardNumber : '',
              交通类型: row.participants && row.participants.transportType ? row.participants.transportType : '',
              航班车次号: row.participants && row.participants.flightTrainNumber ? row.participants.flightTrainNumber : '',
              到达地点: row.participants && row.participants.arrivalLocation ? row.participants.arrivalLocation : '',
              到达时间: row.participants && row.participants.arrivalTime
              ? (() => {
                  const val = row.participants.arrivalTime;
                  const date = new Date(val);
                  if (isNaN(date)) return '';
                  const pad = n => n.toString().padStart(2, '0');
                  return `${date.getFullYear()}/${pad(date.getMonth() + 1)}/${pad(date.getDate())} ` +
                         `${pad(date.getHours())}:${pad(date.getMinutes())}`;
                })()
              : '',
              // 车牌标识: String(row.vehicleId),
              车牌号: row.vehicles && row.vehicles.licensePlate ? row.vehicles.licensePlate : '',
              分配类型: {
                '0': '接站',
                '1': '会议期间',
                '2': '送站'
              }[String(row.assignmentType)] || '未知',
              备注: row.notes || ''
            };
          });
        
          // 没有数据时保留表头
          if (exportData.length === 0) {
            exportData.push({
              // 标识: '',
              // 会议标识: '',
              会议名称: '',
              // 用户标识: '',
              用户姓名: '',
              身份证号: '',
              交通类型: '',
              航班车次号: '',
              到达地点: '',
              到达时间: '',
              // 车牌标识: '',
              车牌号: '',
              分配类型: '',
              备注: ''
            });
          }
        
          // 创建工作表
          const ws = XLSX.utils.json_to_sheet(exportData);
        
          // 设置列宽
          ws['!cols'] = [
            // { wch: 10 },  // 标识
            // { wch: 10 },  // 会议标识
            { wch: 70 },  // 会议名称
            // { wch: 30 },  // 用户标识
            { wch: 15 },  // 用户姓名
            { wch: 20 },  // 身份证号
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            { wch: 20 },
            // { wch: 10 },  // 车牌标识
            { wch: 15 },  // 车牌号
            { wch: 15 },  // 分配类型
            { wch: 30 }   // 备注
          ];
        
          // 设置“标识”列为文本格式防止丢失前导0等
          const header = Object.keys(exportData[0] || {});
          const keys = Object.keys(ws);
          const serialIndex = header.indexOf('标识');
          if (serialIndex >= 0) {
            const serialColLetter = String.fromCharCode(65 + serialIndex);
            keys.forEach(key => {
              if (key.startsWith(serialColLetter) && key !== `${serialColLetter}1`) {
                const cell = ws[key];
                if (cell) {
                  cell.t = 's';
                  cell.z = '@';
                }
              }
            });
          }
        
          // 创建并导出工作簿
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, '派车数据');
          XLSX.writeFile(wb, '派车列表.xlsx');
        })
      },
      //导入
      importFromExcel(e) {
        const file = e.target.files[0];
        if (!file) return;
      
        const reader = new FileReader();
        reader.onload = (event) => {
          const data = new Uint8Array(event.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
        
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
        
          // 读取为 JSON（跳过空行）
          let excelData = XLSX.utils.sheet_to_json(worksheet, { raw: false });
          excelData = excelData.filter(row => {
            return Object.values(row).some(v => v != null && String(v).trim() !== '');
          });
        
          if (!excelData || excelData.length === 0) {
            this.$message.warning('Excel 中无有效数据，无法导入');
            this.$refs.excelInput.value = '';
            return;
          }
        
          // 映射字段
          const mappedData = excelData.map((row, idx) => {
            const assignmentId = Number(row['标识']);
            const conferenceId = Number(row['会议标识']);
            const participantId = Number(row['用户标识']);
            const vehicleId = Number(row['车牌标识']);
            const notes = row['备注'] || '';
          
            // 分配类型中文 → 数字
            const assignmentTypeMap = {
              '接站': 0,
              '会议期间': 1,
              '送站': 2
            };
            const assignmentTypeText = String(row['分配类型'] || '').trim();
            const assignmentType = assignmentTypeMap[assignmentTypeText];
          
            // 校验基本字段
            if (
              isNaN(assignmentId) ||
              isNaN(conferenceId) ||
              isNaN(participantId) ||
              isNaN(vehicleId) ||
              assignmentType === undefined
            ) {
              console.warn(`第 ${idx + 2} 行存在无效数据，跳过该行`, row);
              return null;
            }
          
            return {
              assignmentId,
              conferenceId,
              participantId,
              vehicleId,
              assignmentType,
              notes
            };
          }).filter(item => item !== null);
        
          if (mappedData.length === 0) {
            this.$message.warning('所有行均不符合导入要求，未生成可提交的数据');
            this.$refs.excelInput.value = '';
            return;
          }
        
          // 提交给后端接口
          requests.post('/vehicleAssignment/importAssignmentInfor', mappedData)
            .then(response => {
              this.$message.success(response);
              this.loading(); // 刷新列表
            })
          this.$refs.excelInput.value = '';
        };
      
        reader.readAsArrayBuffer(file);
      },
      //时间格式化
      formatDateTime(row, column, cellValue) {
        if (!cellValue) return '';
        const date = new Date(cellValue);
        const pad = n => n.toString().padStart(2, '0');
        return `${date.getFullYear()}/${pad(date.getMonth() + 1)}/${pad(date.getDate())} ` +
               `${pad(date.getHours())}:${pad(date.getMinutes())}`;
      },
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
